<template>
  <Layout>
    <Dividetb>
      <template #top>
        <TopBox title="用户管理">
          <FilterSearch
            ref="filterSearchRef"
            :placeholder="'请输入用户名称'"
            :searchCallBack="searchCallBack"
          />
          <topButtonGroup :buttonList="tbuttonList" />
          <!-- <div></div> -->
        </TopBox>
      </template>
      <template #bottom>
        <div class="tableBox">
          <el-table
            class="listTable"
            ref="userTable"
            :data="tableData"
            table-layout="auto"
            size="default"
            :border="false"
            @sort-change="handleSortChange"
            @selection-change="handleSelectionChange"
            @row-click="currentRowChange"
            height="81vh"
            @scroll="handleScroll"
          >
            <el-table-column type="selection" width="55" />
            <!-- 序号 -->
            <el-table-column
              label="序号"
              type="index"
              width="60"
              :index="(index) => index + 1"
            />
            <el-table-column prop="userName" label="用户名" />
            <el-table-column prop="nickName" label="姓名" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-value="0"
                  inactive-value="1"
                  :loading="scope.row.statuloading"
                  style="
                    --el-switch-on-color: #0d8afe;
                    --el-switch-off-color: #d2d2d2;
                  "
                  @change="changeStatus(scope.row)"
                  :disabled="scope.row.statuloading || scope.row.userId == 1"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <div class="handle_box d-f jc-c ai-c">
                  <el-button
                    size="small"
                    link
                    @click.stop="handleEdit(scope.$index, scope.row)"
                  >
                    修改
                  </el-button>
                  <el-button
                    size="small"
                    link
                    @click.stop="handleDelete(scope.$index, scope.row)"
                  >
                    删除
                  </el-button>
                  <el-button
                    size="small"
                    link
                    @click.stop="handleReset(scope.$index, scope.row)"
                  >
                    重置密码
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <template #append>
              <div class="load-tip">
                <span v-if="tableLoading">加载中...</span>
                <span v-else-if="!hasMore&&tableData.length>0">没有更多数据了</span>
              </div>
            </template>
          </el-table>
          <New
            :modelValue="editVisible"
            :handle="handle"
            :editData="editData"
            @updateModelValue="changeeditVisible"
            @cancel="cancelEdit"
          />
          <ImportUserPreview
            :visible="importVisible"
            :data="importTable"
            @close="importVisible = false"
          />
          <el-dialog v-model="resetVisible" width="400">
            <p style="margin-bottom: 10px">
              请输入‘{{ currentUserName }}’的新密码
            </p>
            <el-form
              ref="newPasswordform"
              :model="newPassword"
              label-width="auto"
              style="max-width: 600px"
              :rules="newPasswordrule"
            >
              <el-form-item prop="newPassword">
                <el-input
                  v-model="newPassword.newPassword"
                  placeholder="请输入新密码"
                  maxlength="20"
                  show-password
                  autocomplete="off"
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="resetVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmreset">确定</el-button>
              </div>
            </template>
          </el-dialog>
        </div>
      </template>
    </Dividetb>
  </Layout>
</template>
<script setup>
import { ref, toRaw, onMounted, reactive } from "vue";
import { debounce } from "lodash-es";
import {
  More,
  FolderOpened,
  Top,
  EditPen,
  Delete,
  SetUp,
} from "@element-plus/icons-vue";
import { useRoute } from "vue-router";
import NewWindow from "@/assets/customIcon/NewWindow.vue";
import WorkFlow from "@/assets/customIcon/WorkFlow.vue";
import MemberAssignment from "@/assets/customIcon/MemberAssignment.vue";
import useTagStore from "@/stores/tagList";
import Layout from "./layout.vue";
import Dividetb from "@/layout/components/dividetb.vue";
import TopBox from "@/components/TopTitleBox/index.vue";
import FilterSearch from "@/components/TopTitleBox/FilterSearch.vue";
import topButtonGroup from "@/components/ButtonGroup/topButtonGroup.vue";
import New from "../components/newOrChangeUser.vue";
import ImportUserPreview from "../components/ImportedUserPreview.vue";
import { cellMouseEnter, cellMouseLeave } from "@/utils/cellmouseEvent.js";
import { loading } from "@/utils/topButton.js";
import { downloadFile } from "@/utils/download";
import { validateObject, isRed } from "@/utils/validate";
import { parseTime } from "@/utils/common.js";
import {
  getUserList,
  getUserInfoById,
  delUser,
  resetPwd,
  changeUserStatus,
  authRole,
  getRoleByUserId,
  importUserTemplate,
  importUser,
  importDataPreview,
  importData,
  exportUserList,
} from "@/api/account.js";
defineOptions({ name: "MyFolder" });
import router from "@/router";
import { ElMessage } from "element-plus";
const route = useRoute();
const tagStore = useTagStore();
// 分页器相关
const hasMore = ref(true); // 是否还有更多数据
const pagination = reactive({
  pageSize: 20,
  pageNum: 1,
});
const total = ref(0);
const filtrateFormData = reactive({}); // 筛选条件
const tableLoading = ref(false); // 表格数据加载
const tableData = ref([]);
const isLoading = ref(false); // 是否正在加载
const uploadRef = ref(null);
// 按钮列表
const tbuttonList = ref([
  // {
  //   label: "回退",
  //   icon: "el-icon-back",
  //   type: "b2",
  //   onClick: () => {
  //     console.log("点击了回退");
  //     // tagStore.historyBack({
  //     //   name: `/document/l/files${route.query.name}`,
  //     //   breadcrumbName: route.query.name,
  //     // });
  //   },
  // },
  // {
  //   label: "前进",
  //   icon: "el-icon-right",
  //   type: "b2",
  //   onClick: () => {
  //     // tagStore.historyFoward({
  //     //   name: `/document/l/files${route.query.name}`,
  //     //   breadcrumbName: route.query.name,
  //     // });
  //   },
  // },
  {
    label: "添加",
    icon: "el-icon-CirclePlus",
    type: "b2",
    onClick: () => {
      console.log("添加用户");
      handle.value = "添加";
      editVisible.value = true;
    },
  },
  {
    label: "刷新",
    icon: "el-icon-refresh",
    type: "b2",
    onClick: (e) => {
      console.log("点击了刷新");
      // 清空搜索条件
      delete filtrateFormData.params;
      filterSearchRef.value.reset();
      loading(e, () => {
        return new Promise((resolve, reject) => {
          // 清空表格数据

          isLoading.value = true;
          // 重新获取列表数据
          regainData()
            .then((res) => {
              isLoading.value = false;
              ElMessage.success("刷新成功");
              resolve();
            })
            .catch((err) => {
              console.log(err);
              reject();
            });
        });
      });
    },
  },
  {
    label: "下载导入模版",
    icon: "el-icon-Download",
    type: "b2",
    onClick: () => {
      importUserTemplate().then((res) => {
        console.log(res);
        downloadFile(res, "导入模板.xlsx");
      });
    },
  },
  {
    label: "导入",
    icon: "ImportIcon",
    type: "b2",
    upload: true,
    limit: 1,
    ref: "uploadRef",
    onChange: (e, clearFun) => {
      console.log(e, clearFun);

      if (!e.name.includes(".xlsx")) {
        // uploadRef.value.clearFiles();
        // fileData.value = null;
        clearFun();
        return ElMessage.error("请上传模板数据格式的.xlsx文件");
      }
      console.log(e, "3219038910");
      const data = new FormData();
      data.append("file", e.raw);
      data.append("updateSupport", true);
      // uploadRef.value.clearFiles(); //将组件中的文件清空
      // fileData.value = null;
      // fileData.value = e.raw;
      clearFun();

      importDataPreview(data).then(async (res) => {
        if (res.code == 200) {
          console.log(res, "3921793193");

          //!TODO:各数据格式校验，后端该接口只返回解析结果，不进行数据校验
          const result = res.data.map((item) => {
            // item是一条用户数据对象
            const validRes = validateObject(item, validationRules);
            return Object.keys(item).reduce((acc, key) => {
              acc[key] = {
                value: item[key],
                noValidated: validRes[key] ? true : false,
                // noPass: err == key ? false : true,
                noPass: false,
                // errMsg: item.message || validRes[key],
                errMsg: validRes[key] ? validRes[key].join("，") : null,
              };
              return acc;
            }, {});
          });
          console.log(result);
          importTable.value = result;
          importVisible.value = true;
        }
      });
    },
  },
  {
    label: "导出所有用户",
    icon: "exportIcon",
    type: "b2",
    onClick: () => {
      console.log("点击了导出");
      // 获取选中项
      const selectedIds = selectedUserIds.value.join(",");
      // if (selectedIds == "") return ElMessage.error("请选择要导出的日志项");
      // exportUserList({ ids: selectedIds }).then((res) => {
      exportUserList().then((res) => {
        console.log(res);
        downloadFile(
          res,
          "用户列表" + parseTime(new Date(), "{y}-{m}-{d} {h}:{i}")+ ".xlsx"
        );
      });
    },
  },
  {
    label: "批量删除",
    icon: "el-icon-delete",
    type: "b2",
    onClick: () => {
      // 删除选中项
      console.log("点击了批量删除");
      if (selectedUserIds.value.length == 0) {
        ElMessage.warning("请选择要删除的用户");
        return;
      }
      ElMessageBox.confirm("确定要删除这些用户吗？", "", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        icon: "WarnTriangleFilled",
        type: "warning",
      }).then(() => {
        delUser(selectedUserIds.value.join(",")).then((res) => {
          console.log(res);
          if (res.code == 200) {
            ElMessage.success("删除成功");
            regainData();
          } else {
            ElMessage.error("删除失败");
          }
        });
      });
    },
  },
]);
// 校验规则定义
const validationRules = {
  userName: (value) => {
    const errors = [];
    // if (!/^[A-Za-z0-9&]+$/.test(value)) errors.push('只能包含字母、数字和&符号');
    if (!value || value == null || value == undefined || value == "undefined")
      errors.push("用户名不能为空");
    return errors.length ? errors : null;
  },
  nickName: (value) => {
    const errors = [];
    // if (typeof value !== 'string') errors.push('必须是字符串');
    if (value.length > 20) errors.push("昵称不能超过20个字符");
    return errors.length ? errors : null;
  },
  email: (value) => {
    const errors = [];
    if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value))
      errors.push("无效的邮箱格式");
    return errors.length ? errors : null;
  },
  phonenumber: (value) => {
    const errors = [];
    if (!value || value == null || value == undefined || value == "undefined")
      errors.push("联系方式不能为空");
    if (!/^(1[3-9]\d{9})|(0\d{2,4}([- ]?)\d{7,8})$/.test(value))
      errors.push("联系方式格式不正确");
    return errors.length ? errors : null;
  },
};
// 导入
const importVisible = ref(false);
const importTable = ref([]);
const filterSearchRef = ref(null);
const searchCallBack = (word, time) => {
  console.log("搜索回调", word, time);
  ElMessage.info("功能暂未开放，后端传参未知");
  return;
  let params = {};
  if (word) {
    params.searchKey = word;
  }
  if (time) {
    params.startTime = time[0] ? time[0] + " 00:00:00" : null;
    params.endTime = time[1] ? time[1] + " 23:59:59" : null;
  }
  filtrateFormData.nickName = word;
  filtrateFormData.params = params;
  pagination.pageNum = 1;
  hasMore.value = true;
  getUsers();
};
// 新增或修改
const editVisible = ref(false);
const handle = ref("");
const editData = ref({});
const changeeditVisible = (val) => {
  editVisible.value = val;
  hasMore.value = true;
  // 更新列表
  regainData();
};
const cancelEdit = () => {
  editVisible.value = false;
};
const handleEdit = (index, row) => {
  handle.value = "修改";
  editData.value = row;
  editVisible.value = true;
};
const handleDelete = (index, row) => {
  delUser(row.userId).then((res) => {
    // delUser({ userId: row.userId, userLevel: row.userLevel }).then((res) => {
    if (res.code == 200) {
      ElMessage.success("删除成功");
      regainData();
    } else {
      ElMessage.error("删除失败");
    }
  });
};
const currentUser = ref("");
const currentUserName = ref("");
const currentNickName = ref("");
const resetVisible = ref(false);
const newPasswordform = ref(null);
const newPassword = ref({});
const handleReset = (index, row) => {
  console.log(index, row);
  currentUser.value = row.userId;
  currentUserName.value = row.userName;
  currentNickName.value = row.nickName;
  resetVisible.value = true;
};
const confirmreset = () => {
  console.log(newPassword.value);
  newPasswordform.value.validate((valid) => {
    if (valid) {
      resetPwd({
        userId: currentUser.value,
        userName: currentUserName.value,
        nickName: currentNickName.value,
        password: newPassword.value.newPassword,
        userLevel: "0",
      }).then((res) => {
        console.log(res);
        if (res.code == 200) {
          ElMessage.success("重置密码成功");
          resetVisible.value = false;
        }
      });
    }
  });
};
const changeStatus = (user) => {
  console.log(user, "changeStatus");
  // 将对应switch按钮设置为loading状态
  tableData.value = tableData.value.map((item) => {
    if (item.userId === user.userId) {
      item.statuloading = true;
    }
    return item;
  });
  // 调接口
  let data = {
    // userName: user.userName,
    // nickName: user.nickName,
    userId: user.userId,
    userLevel: user.userLevel,
    status: user.status, //组件会将值修改，于是直接用组件的值
  };
  changeUserStatus(data)
    .then((res) => {
      console.log(res);
      if (res.code == 200) {
        // regainData()// 获取整个列表消耗太大
        tableData.value = tableData.value.map((item) => {
          if (item.userId === data.userId) {
            item.statuloading = false;
          }
          return item;
        });
        ElMessage.success("修改状态成功");
      } else {
        // 改回去
        tableData.value = tableData.value.map((item) => {
          if (item.userId === data.userId) {
            item.statuloading = false;
            item.status = data.status == "0" ? "1" : "0";
          }
          return item;
        });
      }
    })
    .catch((err) => {
      // 改回去
      tableData.value = tableData.value.map((item) => {
        if (item.userId === data.userId) {
          item.statuloading = false;
          item.status = data.status == "0" ? "1" : "0";
        }
        return item;
      });
    });
};
const regainData = () => {
  tableData.value = [];
  pagination.pageNum = 1;
  delete filtrateFormData.params;
  delete filtrateFormData.nickName;
  hasMore.value = true;
  return getUsers();
};
// 滚动事件处理（带防抖）
const handleScroll = debounce((e) => {
  console.log("滚动事件触发", e);
  // 距离底部 300px 时触发
  const bottomThreshold = 300;
  const container = document.querySelector(".listTable .el-scrollbar");
  const parent = document.querySelector(".listTable tbody");
  console.log(container, parent);
  const conRect = container.getBoundingClientRect();
  const parentRect = parent.getBoundingClientRect();
  console.log(conRect, parentRect);
  if (parentRect.bottom - conRect.bottom <= bottomThreshold) {
    console.log("到底了");
    loadMore();
  }
}, 100);
const loadMore = () => {
  if (!hasMore.value || tableLoading.value) return;
  // 获取下一页列表数据
  getMyFolderList();
};
const getUsers = () => {
  return new Promise((resolve, reject) => {
    if (!hasMore.value) return;
    let params = { ...pagination, ...filtrateFormData };
    tableLoading.value = true;
    getUserList(params)
      .then((res) => {
        if (res.code == 200) {
          if (pagination.pageNum == 1) {
            tableData.value = res.rows;
          } else {
            tableData.value = [...tableData.value, ...res.rows];
          }
          total.value = res.total;
          hasMore.value = total.value > tableData.value.length;
          pagination.pageNum++;
        }
        resolve(res);
      })
      .catch((err) => {
        console.error(err);
        reject(err);
      })
      .finally(() => {
        setTimeout(() => {
          tableLoading.value = false;
        }, 800);
      });
  });
};
/** 排序触发事件 */
function handleSortChange(column, prop, order) {
  filtrateFormData.orderByColumn = column.prop;
  filtrateFormData.isAsc = column.order;
  setCondition2();
}
const selectedUserIds = ref([]);
const multiple = ref(true);
// const once = ref(true);
const userTable = ref(null);
// 多选框选中数据
function handleSelectionChange(selection) {
  selectedUserIds.value = selection.map((item) => item.userId);
  multiple.value = !selection.length;
}
const currentRowChange = (curRow) => {
  console.log(curRow);
  const flag = selectedUserIds.value.includes(curRow.userId);
  userTable.value.toggleRowSelection(curRow, !flag);
};
onMounted(() => {
  console.log("我的文件夹页面挂载完成");
  getUsers();
});
</script>
<style lang="scss" scoped>
.tableBox {
  :deep(.cell) {
    display: flex;
    justify-content: center;
    // font-size: var(--el-font-size-base);
  }
  :deep(.zhiding) {
    border-bottom: none !important;
  }
  .moreBtn {
    display: none;
    &.active {
      display: flex;
    }
  }
}
</style>
